package com.hippy.erya.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hippy.erya.base.auth.context.LoginContextHolder;
import com.hippy.erya.entity.MessageDO;
import com.hippy.erya.mapper.MessageMapper;
import com.hippy.erya.query.BaseQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, MessageDO> {

    @Autowired
    private MessageMapper messageMapper;

    public Page<MessageDO> queryByPage(Long currentPage, int limit) {
        Page<MessageDO> page = new Page<>(currentPage, limit);
        QueryWrapper<MessageDO> queryWrapper = BaseQueryWrapper.buildQuery();
        Page<MessageDO> pageResult = messageMapper.selectPage(page, queryWrapper);
        pageResult.getRecords().forEach(BaseQueryWrapper::outputMessage);
        return pageResult;
    }

    public void insert(MessageDO messageDO) {
        messageMapper.insert(messageDO);
    }

    public void updateMessage(String[] idArray) {
        String userId = String.valueOf(LoginContextHolder.getContext().getUserId());
        for (String id : idArray) {
            if (!StringUtils.isNumeric(id)) {
                continue;
            }
            MessageDO messageDO = messageMapper.selectById(Long.valueOf(id));
            messageDO.setStatus("已读");
            messageDO.setUpdatedAt(new Date());
            messageDO.setUpdatedBy(userId);
            messageMapper.updateById(messageDO);
        }
    }


    public Pair<Integer, List<MessageDO>> queryLatestMessage() {
        QueryWrapper<MessageDO> queryWrapper = BaseQueryWrapper.buildQuery();
        queryWrapper.eq("STATUS", "未读");
        int totalCount = messageMapper.selectCount(queryWrapper);
        queryWrapper.last("limit 3");
        List<MessageDO> list = messageMapper.selectList(queryWrapper);
        return Pair.of(totalCount, list);
    }

}
